package net.chenlin.dp.ids.client.servlet;

import net.chenlin.dp.ids.client.config.PassportClientConfig;
import net.chenlin.dp.ids.client.manager.AuthCheckManager;
import net.chenlin.dp.ids.client.util.MaskUtil;
import net.chenlin.dp.ids.common.base.BaseResult;
import net.chenlin.dp.ids.common.constant.GlobalErrorEnum;
import net.chenlin.dp.ids.common.constant.IdsConst;
import net.chenlin.dp.ids.common.entity.SessionData;
import net.chenlin.dp.ids.common.util.CommonUtil;
import net.chenlin.dp.ids.common.util.JsonUtil;
import net.chenlin.dp.ids.common.util.WebUtil;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * web用户登录状态校验servlet，返回json支持跨域
 * @author zcl<yczclcn@163.com>
 */
public class WebAuthStatusServlet extends HttpServlet {

    private PassportClientConfig clientConfig;

    private AuthCheckManager authCheckManager;

    private static final long serialVersionUID = 8700620723419494542L;

    public WebAuthStatusServlet(PassportClientConfig clientConfig, AuthCheckManager authCheckManager) {
        this.clientConfig = clientConfig;
        this.authCheckManager = authCheckManager;
    }

    /**
     * get请求
     * @param req
     * @param resp
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String callback = req.getParameter(IdsConst.JSONP_DEFAULT_CALLBACK);
        if (CommonUtil.strIsEmpty(callback)) {
            callback = IdsConst.JSONP_DEFAULT_CALLBACK;
        }
        // 客户端登录校验
        SessionData sessionData = (SessionData) req.getAttribute(IdsConst.SESSION_KEY);

        // 客户端已登录
        if (sessionData != null) {
            handlerAuthStatusRequest(resp, callback, true, sessionData.getUserAlias());
            return;
        }

        // ajax请求直接返回jsonp
        if (WebUtil.isAjax(req)) {
            handlerAuthStatusRequest(resp, callback, false, null);
        } else {
            // 服务端登录校验
            String idsLogin = req.getParameter("idsLogin");
            if (CommonUtil.strIsNotEmpty(idsLogin) && !Boolean.parseBoolean(idsLogin)) {
                handlerAuthStatusRequest(resp, callback, false, null);
                return;
            }
            // 未登录，且无服务端未登录状态，重定向认证中心登录
            String authStatusLogin = WebUtil.requestAppendParam(
                    clientConfig.getAuthServerUrl() + IdsConst.LOGIN_URL,
                    new String[]{IdsConst.REDIRECT_KEY, IdsConst.GATEWAY_KEY, IdsConst.TARGET_KEY},
                    new Object[]{clientConfig.getServerName() + IdsConst.AUTH_URL, "true",
                            clientConfig.getServerName() + IdsConst.AUTH_STATUS_URL});
            resp.sendRedirect(resp.encodeRedirectURL(authStatusLogin));
        }

    }

    /**
     * post请求
     * @param req
     * @param resp
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        this.doGet(req, resp);
    }

    /**
     * 返回未登录jsonp
     * @param resp
     * @param callback
     */
    private void handlerAuthStatusRequest(HttpServletResponse resp, String callback, boolean hasLogin, String userAlias) {
        Map<String, Object> authRes = new HashMap<>(3);
        authRes.put("authStatusResponse", true);
        authRes.put("hasLogin", hasLogin);
        authRes.put("userName", MaskUtil.maskUserAlias(userAlias));
        String json = WebUtil.jsonp(callback, JsonUtil.toStr(authRes));
        WebUtil.write(resp, json);
    }

}
